package cn.sumpu.app.guoguojie.biz.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import cn.sumpu.app.guoguojie.biz.AccountBiz;
import cn.sumpu.app.guoguojie.biz.ExchangeBiz;
import cn.sumpu.app.guoguojie.biz.ProductBiz;
import cn.sumpu.app.guoguojie.dao.ProductDao;
import cn.sumpu.app.guoguojie.domain.Account;
import cn.sumpu.app.guoguojie.domain.Member;
import cn.sumpu.app.guoguojie.domain.Order;
import cn.sumpu.app.guoguojie.domain.OrderProduct;
import cn.sumpu.app.guoguojie.domain.Product;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;
import cn.sumpu.app.guoguojie.util.Common;
import cn.sumpu.app.guoguojie.util.PageModel;

public class ProductBizImpl implements ProductBiz{
	private static Logger logger = LoggerFactory
	.getLogger(ProductBizImpl.class);
	
	private ProductDao productDao;

	public void setProductDao(ProductDao productDao) {
		this.productDao = productDao; 
	}
	private DataSourceTransactionManager transactionManager;

	public void settransactionManager(DataSourceTransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}
	@Override
	public void insertNewProduct(Product product)throws AppBusinessException{
		productDao.insertNewProduct(product);
	}
	@Autowired
	private AccountBiz accountBiz;
	@Autowired
	private ExchangeBiz exchangBiz;
	
	//查询所有商品
	@Override
	public List<Product> selectProductList(Map<String, Object> map)throws AppBusinessException {
		 
		  List<Product> productList = productDao.selectProductList(map);
		  	for (Product productOne :productList){
		  		int num =productOne.getMemberList().size();
		  		productOne.setPersonNum(num);
		  	}
		  return  productList;
	}
	/**
	 * 
	 */
	@Override
	public PageModel selectProductPm(Integer page)throws AppBusinessException {
		    PageModel pm = new PageModel();
		    int pageSize =10;
			int startId = (page - 1) * pageSize;
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("startId", startId);
			map.put("pageSize", pageSize);
			map.put("category", "01");
			map.put("isClosed", "false");
			map.put("enabled", "true");
		    List<Product> productList = productDao.selectProductList(map);
			Integer commentCount =countProductList(map);
		    pm.setCurrentPage(page);
			pm.setList(productList); 
			pm.setPageSize(pageSize);    
			pm.setTotalRecord(commentCount); 
			pm.setTotalPage((commentCount + pageSize - 1) / pageSize);
		  	for (Product productOne :productList){
		  		int num =productOne.getMemberList().size();
		  		productOne.setPersonNum(num);
		  	}
		  return  pm;
	}
	
	
	
	//查询今日推荐商品
	@Override
	public Product selectRecommendProduct()throws AppBusinessException {
		Product product =productDao.selectRecommendProduct();
		if(product!=null){
			int num =product.getMemberList().size();
			product.setPersonNum(num);
		}
		return product;
	}
	
	
	//查询所有商品总数
	@Override
	public Integer countProductList(Map<String,Object> map)throws AppBusinessException {
		return productDao.countProductList(map);
	}
	//删除产品
	@Override
	public void deleteProductById(String identifier)throws AppBusinessException{
		productDao.deleteProductById(identifier);
	}
	//查询某一产品的详情
	@Override
	public Product selectProduct(String identifier)throws AppBusinessException{
		return productDao.selectProduct(identifier);
	}
	//查询某一订单的详情
	@Override
	public Order selectViewOrder(String orderId)throws AppBusinessException{
		return productDao.selectViewOrder(orderId);
	}
	
	//更新某一产品
	@Override
	public void updateProductById(Product product)throws AppBusinessException {
		
		productDao.updateProductById(product);
	}
	//今日推荐
	@Override
	public void recommendProduct(String productId)throws AppBusinessException {
		productDao.updateIsClosed();
		Product product =new Product();
		product.setIdentifier(productId);
		product.setIsClosed(true); 
		productDao.updateProductById(product);
	}
	
	//更新订单状态
	@Override
	public void updateOrderStatus(String identifier,String status)throws AppBusinessException {
		Order order =new Order();
		order.setIdentifier(identifier);
		order.setStatus(status);
		productDao.updateOrder(order);
	}
	
	//添加一新订单
	@Override
	public void insertOrder(Order order,OrderProduct orderProduct)throws AppBusinessException{
		Product product =productDao.selectProductByName(orderProduct.getProduct());
		order.setType(product.getCategory()); 
		productDao.insertOrder(order);
		orderProduct.setOrder(order.getIdentifier());
		orderProduct.setProduct(product.getIdentifier());
		productDao.insertOrderProduct(orderProduct);
	}
	//添加一新订单（红利会）
		@Override
		public void insertOrderForRed(Order order,OrderProduct orderProduct)throws AppBusinessException{
			
			productDao.insertOrder(order);
			productDao.insertOrderProduct(orderProduct);
		}
	//更新订单
	@Override
	public void updateOrderByOrderId(Order order,OrderProduct orderProduct)throws AppBusinessException{
		//更新后的产品类型
		Product product =productDao.selectProductByName(orderProduct.getProduct());
		order.setType(product.getCategory());
		productDao.updateOrder(order);
		orderProduct.setOrder(order.getIdentifier());
		//更新后的产品
		orderProduct.setProduct(product.getIdentifier());
		//根据订单号修改订单产品
		productDao.updateOrderProduct(orderProduct);
	}
	//查询所有订单(Map)
	@Override
	public PageModel selectOrderListPageModel(Integer page,String familyId,String startDate,String endDate)throws AppBusinessException{
		int pageSize = 6;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("startId", (page - 1) * pageSize);
		map.put("pageSize", pageSize);
		map.put("family", familyId); 
		//时间查询
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
		try {
			if(Common.notEmptyStr(startDate)){
				map.put("startDate", dateFormat.parse(startDate));
			}
			if(Common.notEmptyStr(endDate)){
				map.put("endDate", dateFormat.parse(endDate));
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} 
		List<Order> orderlist = productDao.selectOrderList(map);
		
		if(orderlist.size()>0){
			for(Order orderOne:orderlist){
				String type = orderOne.getType();
				if(("01").equals(type)){ 
					Map<String ,Object> mapStatus=new HashMap<String, Object>();
					mapStatus.put("01", "填写地址");
					mapStatus.put("02", "等待发货");
					mapStatus.put("03", "已发货");
					mapStatus.put("04", "已完成");
					mapStatus.put("05", "已取消");
					OrderProduct orderProduct=productDao.selectOrderProductByOrderId(orderOne.getIdentifier());
					//产品
					Product product=productDao.selectProduct(orderProduct.getProduct());
				    orderOne.setProductName(product.getTitle());
					orderOne.setMapStatus(mapStatus);
				}else if(("02").equals(type)||("06").equals(type)){
					Map<String ,Object> mapStatus=new HashMap<String, Object>();
					mapStatus.put("01", "填写地址");
					mapStatus.put("02", "等待发货");
					mapStatus.put("03", "已发货");
					mapStatus.put("06", "等待点评");
					mapStatus.put("04", "已完成");
					mapStatus.put("05", "已取消");
					orderOne.setProductName(orderOne.getTitle());
					orderOne.setMapStatus(mapStatus);
				}else if(("03").equals(type)){
					Map<String ,Object> mapStatus=new HashMap<String, Object>();
					mapStatus.put("01", "填写地址");
					mapStatus.put("02", "等待发货");
					mapStatus.put("03", "已发货");
					mapStatus.put("04", "已完成");
					mapStatus.put("05", "已取消");
					orderOne.setMapStatus(mapStatus);
				}else if(("04").equals(type)){
					Map<String ,Object> mapStatus=new HashMap<String, Object>();
					mapStatus.put("01", "填写地址");
					mapStatus.put("02", "等待发货");
					mapStatus.put("03", "已发货");
					mapStatus.put("04", "已完成");
					mapStatus.put("05", "已取消");
					orderOne.setMapStatus(mapStatus);
				}else if(("05").equals(type)){
					Map<String ,Object> mapStatus=new HashMap<String, Object>();
					mapStatus.put("07", "填写电话");
					mapStatus.put("08", "已预定");
					mapStatus.put("09", "已参与");
					mapStatus.put("10", "没参与");
					mapStatus.put("05", "已取消");
					orderOne.setMapStatus(mapStatus);
				}
			}
			
		}
		int orderCount = productDao.selectOrderListCount(map);
		PageModel pm = new PageModel();
		pm.setList(orderlist);
		pm.setCurrentPage(page);
		pm.setTotalRecord(orderCount);
		pm.setPageSize(pageSize);
		pm.setTotalPage((orderCount + pageSize - 1) / pageSize);
		return pm;
	}
	
	@Override
	public void order(Order order,OrderProduct orderProduct)throws AppBusinessException {
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();// 事务定义类
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);// 设置事务传播属性
		TransactionStatus status = transactionManager.getTransaction(def);// 返回事务对象
		try{ 
			//产品详情
			Product product=productDao.selectProduct(orderProduct.getProduct());
			//数量  
			int amount =Integer.valueOf(orderProduct.getQuantity());
			//总价
			//家庭号 
			//交易摘要
			double money =product.getPrice()*amount;
			String familyId =order.getFamily();
			String summary = "兑换"+amount+"个【"+product.getTitle()+"】";
			
//			Account myAccount = accountBiz.getAccountByMember(familyId);
//			if (myAccount.getRmb() < money) {
//				double ggb = exchangBiz.exchangeRmbToGgb(money - myAccount.getRmb());
//				accountBiz.ggb2RmbByFamily(familyId, ggb, "兑换【"+product.getTitle()+"】时系统自动转换");
//			}
//			accountBiz.transferRmbByFamily(familyId, Common.GUOUOJIE_COST_ACCOUNT, money, summary, null);
			
			product.setAmount(product.getAmount()-amount);
			productDao.updateProductById(product);
			order.setTitle(product.getTitle());
			order.setType(product.getCategory());
			productDao.insertOrder(order);
			orderProduct.setOrder(order.getIdentifier());
			productDao.insertOrderProduct(orderProduct);
			transactionManager.commit(status);// 提交事务
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("Order fail",e);
			}
			transactionManager.rollback(status);// 回滚事务
			throw new AppBusinessException(e);
		}
		
	}
	//取消订单 
	@Override
	public void cancelOrder(String orderId)throws AppBusinessException{
		
			DefaultTransactionDefinition def = new DefaultTransactionDefinition();// 事务定义类
			def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);// 设置事务传播属性
			TransactionStatus status = transactionManager.getTransaction(def);// 返回事务对象
			try{   
			Order order =productDao.selectViewOrder(orderId);
			OrderProduct orderProduct=productDao.selectOrderProductByOrderId(orderId);
			//产品  
			String productId =orderProduct.getProduct();
			Product product =productDao.selectProduct(productId);
			//家庭号 
			String familyId=order.getFamily();
			//产品数量
			int amount =Integer.valueOf(order.getProductQuantity());
			double money =product.getPrice()*amount;
			String summary = "取消"+amount+"个【"+product.getTitle()+"】";
			product.setAmount(product.getAmount()+amount);
			//更新数量+
			productDao.updateProductById(product);
			//还钱 
//			accountBiz.transferRmbByFamily(Common.GUOUOJIE_COST_ACCOUNT, familyId, money, summary, null);
			//删除订单 
			productDao.deleteOrderById(orderId); 
			productDao.deleteOrderProductById(orderId);
			transactionManager.commit(status);// 提交事务
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("Cancel order fail",e);
			}
			transactionManager.rollback(status);// 回滚事务
			throw new AppBusinessException(e);
		}
	}
	//查询兑换达人
	@Override
	public List<Member>selectOrderMemberList()throws AppBusinessException{
		Map<String ,Object> map=new HashMap<String, Object>();
		map.put("type", "01");
		return productDao.getOrderMemberList(map);
	}
	
}
